package com.happyhell.hiyou.util;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

public class SqlSessionUtil {

	private static String RESOURCE = "mybatis-config.xml";
	private static Reader reader = null;
	private static SqlSessionFactory sessionFactory = null;
	private static Logger logger = LogManager.getLogger(SqlSessionUtil.class);
	
	public static SqlSession getSession() {
		try {
			if (reader == null) {
				logger.debug("Start to init sqlSessionFactory.");
				reader = Resources.getResourceAsReader(RESOURCE);
				sessionFactory = new SqlSessionFactoryBuilder().build(reader);
				logger.debug("Init sqlSessionFactory successfully.");
			}
			return sessionFactory.openSession();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			return null;
		}  
	}
	
}
